package cn.wolfcode.luowowo.comment.service.impl;

import cn.wolfcode.luowowo.comment.domain.TravelComment;
import cn.wolfcode.luowowo.comment.query.TravelCommentQuery;
import cn.wolfcode.luowowo.comment.repository.TravelCommentRepository;
import cn.wolfcode.luowowo.comment.service.ITravelCommentService;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
public class ITravelCommentServiceImpl implements ITravelCommentService {
    @Autowired
    private TravelCommentRepository repository;
    @Autowired
    private MongoTemplate template;

    @Override
    public TravelComment saveOrUpdate(TravelComment travelComment) {
        travelComment.setCreateTime( new Date() );
        if (travelComment.getType() == TravelComment.TRAVLE_COMMENT_TYPE) {
            TravelComment refcomment = repository.findById( travelComment.getRefComment().getId() ).get();
            travelComment.setRefComment( refcomment );

        }
        repository.save( travelComment );
        return travelComment;
    }

    @Override
    public Page <TravelComment> query(TravelCommentQuery qo) {
        Query query = new Query();
        query.addCriteria( Criteria.where( "travelId" ).is( qo.getTravelId() ) );
        //根据query 这个条件去查满足条件的数量
        long total = template.count( query, TravelComment.class );
        if (total == 0) {
            return Page.empty();
        }
        //查list
        //添加分页
        Pageable pageable = PageRequest.of( qo.getCurrentPage() - 1, qo.getPageSize(), Sort.Direction.ASC, "createTime" );
        query.with( pageable );
        List <TravelComment> travelComments = template.find( query, TravelComment.class );
        return new PageImpl <>( travelComments, pageable, total );
    }

    @Override
    public long getCount(Long travelId) {
        Query query = new Query();
        query.addCriteria( Criteria.where( "travelId" ).is( travelId ) );
        //查count
        long count = template.count( query, TravelComment.class );
        return count;
    }

    @Override
    public List <TravelComment> selectNewCommentTop10() {
        Query query = new Query();
        query.skip( 0 ).limit( 10 );
        query.with( Sort.by( Sort.Direction.DESC, "createTime" ) );
        List <TravelComment> travelComments = template.find( query, TravelComment.class );
        return travelComments;
    }


}
